import { View } from '@tarojs/components';
import { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { APPKEY, PLATFORM, SDTFORM } from './business-config';
import type { Ref } from 'react';
import type { ISuperPlayerConfig } from '@tencent/super-player';
import type SuperPlayer from '@tencent/super-player';

import $style from './index.scss';

const SuperPlayerESM =
    process.env.TARO_ENV === 'h5' ? require('@tencent/super-player').default : null;

export interface KVideoRef {
    getInstance: () => SuperPlayer | null;
}
type KVideoProps = Omit<ISuperPlayerConfig, 'container'> & {
    vid?: string;
};
function Video(props: KVideoProps, ref: Ref<KVideoRef>) {
    if (!SuperPlayerESM) {
        return <View className={$style['no-support']}>当前环境不支持视频播放</View>;
    }
    const { vid } = props;

    const playerRef = useRef<SuperPlayer | null>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    function initPlayer() {
        if (!containerRef.current) return;
        if (!playerRef.current) {
            const innerConf = {
                container: containerRef.current, // css module导致classname有不确定的后缀，所以传入DOM元素
                businessConfig: {
                    appKey: APPKEY,
                    platform: PLATFORM,
                    sdtfrom: SDTFORM
                }
            };
            const config = {
                ...innerConf,
                ...props
            };
            const player = new SuperPlayerESM(config) as SuperPlayer;
            playerRef.current = player;
        }
        if (!vid) return;
        playerRef.current.play(vid);
    }
    function getInstance() {
        return playerRef.current;
    }
    useEffect(() => {
        initPlayer();
    }, [vid]);
    useImperativeHandle(ref, () => {
        return {
            getInstance
        };
    });
    return (
        <View
            className={$style.video}
            ref={containerRef}
        ></View>
    );
}

const KVideo = forwardRef(Video);
export default KVideo;
